import React, { useMemo, useState } from 'react';
import { Tooltip, Select } from 'antd';

interface ContributionCalendarProps {
  experiments: Array<{ created_at: string }>;
  startDate?: Date;
  endDate?: Date;
}

interface DayData {
  date: Date;
  count: number;
  dateString: string;
}

const ContributionCalendar: React.FC<ContributionCalendarProps> = ({
  experiments,
}) => {
  // 默认显示当前年份（全年 12 个月）
  const today = new Date();
  const [currentYear, setCurrentYear] = useState(today.getFullYear());

  // 统计每天的实验数量（全量，用于全年）
  const dayDataMap = useMemo(() => {
    const map = new Map<string, number>();
    experiments.forEach(exp => {
      const date = new Date(exp.created_at);
      const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      map.set(dateKey, (map.get(dateKey) || 0) + 1);
    });
    return map;
  }, [experiments]);

  // 工具：整年的所有显示天（从年首前置到周一，到年末后置到周日）
  const yearDays = useMemo(() => {
    const firstDay = new Date(currentYear, 0, 1);
    const lastDay = new Date(currentYear, 11, 31);
    const startDow = firstDay.getDay();
    const daysToMonday = startDow === 0 ? 6 : startDow - 1;
    const startMonday = new Date(firstDay);
    startMonday.setDate(firstDay.getDate() - daysToMonday);

    const endDow = lastDay.getDay();
    const daysToSunday = endDow === 0 ? 0 : 7 - endDow;
    const endSunday = new Date(lastDay);
    endSunday.setDate(lastDay.getDate() + daysToSunday);

    const res: DayData[] = [];
    const iter = new Date(startMonday);
    while (iter <= endSunday) {
      const dateKey = `${iter.getFullYear()}-${String(iter.getMonth() + 1).padStart(2, '0')}-${String(iter.getDate()).padStart(2, '0')}`;
      res.push({
        date: new Date(iter),
        count: dayDataMap.get(dateKey) || 0,
        dateString: dateKey,
      });
      iter.setDate(iter.getDate() + 1);
    }
    return res;
  }, [currentYear, dayDataMap]);

  // 计算全年最大数量，用于颜色分级统一尺度
  const maxCount = useMemo(() => {
    return Math.max(...yearDays.map(d => d.count), 1);
  }, [yearDays]);

  // 获取颜色等级（类似 GitHub 的4级颜色）
  const getColorLevel = (count: number): string => {
    if (count === 0) return '#ebedf0'; // 无数据：浅灰
    
    const level = Math.ceil((count / maxCount) * 4);
    
    switch (level) {
      case 1:
        return '#9be9a8'; // 少：浅绿
      case 2:
        return '#40c463'; // 中：绿色
      case 3:
        return '#30a14e'; // 多：深绿
      case 4:
      default:
        return '#216e39'; // 最多：最深绿
    }
  };

  // 将全年组织为按周二维数组（每列一周、每行一个星期几）
  const weeks = useMemo(() => {
    const weeksList: DayData[][] = [];
    let currentWeek: DayData[] = [];
    yearDays.forEach(d => {
      currentWeek.push(d);
      if (currentWeek.length === 7) {
        weeksList.push(currentWeek);
        currentWeek = [];
      }
    });
    if (currentWeek.length > 0) {
      while (currentWeek.length < 7) {
        const lastDay = currentWeek[currentWeek.length - 1];
        const nextDate = new Date(lastDay.date);
        nextDate.setDate(nextDate.getDate() + 1);
        const dateKey = `${nextDate.getFullYear()}-${String(nextDate.getMonth() + 1).padStart(2, '0')}-${String(nextDate.getDate()).padStart(2, '0')}`;
        currentWeek.push({
          date: nextDate,
          count: 0,
          dateString: dateKey,
        });
      }
      weeksList.push(currentWeek);
    }
    return weeksList;
  }, [yearDays]);

  // 格式化日期显示
  const formatDate = (date: Date): string => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${month}月${day}日`;
  };

  // 顶部月份标签（定位在每个月第一次出现的周列）
  const monthLabels = useMemo(() => {
    const labels: { weekIndex: number; month: string }[] = [];
    let lastMonth = -1;
    weeks.forEach((week, idx) => {
      // 找到这一列中属于当前年份的任意一天，取其月份
      const inYearDay = week.find(d => d.date.getFullYear() === currentYear);
      if (!inYearDay) return;
      const m = inYearDay.date.getMonth();
      if (m !== lastMonth) {
        labels.push({ weekIndex: idx, month: `${m + 1}月` });
        lastMonth = m;
      }
    });
    return labels;
  }, [weeks, currentYear]);

  // 每列像素宽度（方块12px + 列间距2px）
  const columnWidth = 14;
  const contentWidth = useMemo(() => weeks.length * columnWidth, [weeks.length]);

  // 生成年份选项（仅当前年与上一年）
  const yearOptions = useMemo(() => {
    const today = new Date();
    const currentYearNum = today.getFullYear();
    return [
      { label: `${currentYearNum}年`, value: currentYearNum },
      { label: `${currentYearNum - 1}年`, value: currentYearNum - 1 },
    ];
  }, []);
  
  // 计算当前年份的实验数量
  const currentYearExperimentCount = useMemo(() => {
    return experiments.filter(exp => {
      const expDate = new Date(exp.created_at);
      return expDate.getFullYear() === currentYear;
    }).length;
  }, [experiments, currentYear]);

  return (
    <div className="contribution-calendar" style={{ width: 'fit-content', maxWidth: '100%' }}>
      <div className="contribution-calendar-header">
        <div className="calendar-title">
          <span style={{ fontSize: '14px', fontWeight: 600 }}>实验提交日历</span>
          <span style={{ fontSize: '12px', color: '#666', marginLeft: '8px' }}>
            {currentYear} 年共 {currentYearExperimentCount} 个实验
          </span>
        </div>
        <div className="calendar-controls">
          <Select
            value={currentYear}
            onChange={setCurrentYear}
            options={yearOptions}
            style={{ width: 100 }}
            size="small"
          />
        </div>
        <div className="calendar-legend">
          <span style={{ fontSize: '12px', color: '#666', marginRight: '8px' }}>少</span>
          <div className="legend-squares">
            <div className="legend-square" style={{ backgroundColor: '#9be9a8' }}></div>
            <div className="legend-square" style={{ backgroundColor: '#40c463' }}></div>
            <div className="legend-square" style={{ backgroundColor: '#30a14e' }}></div>
            <div className="legend-square" style={{ backgroundColor: '#216e39' }}></div>
          </div>
          <span style={{ fontSize: '12px', color: '#666', marginLeft: '8px' }}>多</span>
        </div>
      </div>

      <div className="contribution-calendar-body">
        <div className="calendar-layout">
          <div className="calendar-weekdays">
            <div className="weekday-spacer"></div>
            <div className="weekday-label"></div>
          </div>
          <div className="calendar-content" style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
            {/* 统一的水平滚动容器（月份标签和网格一起滚动）*/}
            <div style={{ overflowX: 'auto', maxWidth: '100%' }}>
              <div style={{ width: contentWidth + 28, position: 'relative' }}>
                {/* 顶部月份标签 */}
                <div className="month-labels-row" style={{ marginBottom: 6 }}>
                  <div className="month-label-spacer" style={{ width: 28 }}></div>
                  <div className="month-labels-container" style={{ position: 'relative', height: 16 }}>
                    {monthLabels.map((label, index) => (
                      <div
                        key={index}
                        className="month-label"
                        style={{ position: 'absolute', left: `${label.weekIndex * columnWidth}px`, fontSize: 12, color: '#666' }}
                      >
                        {label.month}
                      </div>
                    ))}
                  </div>
                </div>

                {/* 主网格：全年拼接成一条长的周列序列 */}
                <div className="calendar-grid-main">
                  {[
                    { day: 1, label: '周一' },
                    { day: 2, label: '' },
                    { day: 3, label: '周三' },
                    { day: 4, label: '' },
                    { day: 5, label: '周五' },
                    { day: 6, label: '' },
                    { day: 0, label: '' },
                  ].map(({ day: dayOfWeek, label: dayLabel }) => (
                    <div key={dayOfWeek} style={{ display: 'flex', alignItems: 'center', marginBottom: 2 }}>
                      <div style={{ width: 28, fontSize: 11, color: '#888' }}>{dayLabel}</div>
                      <div style={{ display: 'flex', gap: 2 }}>
                        {weeks.map((week, colIndex) => {
                          const dayIndexInWeek = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
                          const day = week[dayIndexInWeek];
                          const inYear = day.date.getFullYear() === currentYear;
                          const color = getColorLevel(day.count);
                          return (
                            <Tooltip
                              key={`${colIndex}-${dayOfWeek}`}
                              title={inYear ? `${formatDate(day.date)}: ${day.count} 个实验` : ''}
                            >
                              <div
                                className="calendar-day"
                                style={{
                                  width: 12,
                                  height: 12,
                                  backgroundColor: inYear ? color : '#ebedf0',
                                  opacity: inYear ? 1 : 0.5,
                                  borderRadius: 2,
                                  flex: '0 0 auto',
                                }}
                              />
                            </Tooltip>
                          );
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ContributionCalendar;

